import { resourceTree } from '@/api'
import { _import } from '../router/map'
import Layout from '@/layout'
import { constRoutes } from '@/router'

const state = {
  routes: [], // 完整路由表
  addRoutes: [], // 用户可访问路由表
  buttons: JSON.parse(localStorage.getItem('buttons')) || [],
}

const mutations = {
  setRoutes: (state, routes) => {
    state.addRoutes = routes
    state.routes = constRoutes.concat(routes)
  },
  setButtons: (state, buttons) => {
    state.buttons = buttons
  },
}

const actions = {
  generateRoutes({ commit }) {
    return new Promise((resolve, reject) => {
      resourceTree()
        .then((res) => {
          console.log('res', res)
          if (res.code == 200) {
            const vueRouter = res.data.vueRouter.slice(1)
            const buttons = res.data.button
            const accessedRoutes = filterAsyncRouter(vueRouter)
            commit('setRoutes', accessedRoutes)
            commit('setButtons', buttons)
            localStorage.setItem('buttons', JSON.stringify(buttons))
            resolve(accessedRoutes)
          }
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
}


function filterAsyncRouter(asyncRouterMap) {
    //遍历后台传来的路由字符串，转换为组件对象
    const accessedRouters = asyncRouterMap.filter((route) => {
      if (route.component && route.resourceType == 1) {
        if (route.component === 'Layout') {
          //Layout组件特殊处理
          route.component = Layout
        } else {
          route.component = _import(route.component)
        }
      }
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children)
      }
      return true
    })
    
    return accessedRouters
  }

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
